package current.queues;

import java.util.StringJoiner;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueDemo {

    /**
     * 简单的实现一个延迟队列
     */
    static class DelayedItem<T> implements Delayed {

        T value;
        long time = 0;

        public DelayedItem(T value, long delay) {
            this.value = value;
            this.time = delay + System.currentTimeMillis();
        }

        @Override
        public String toString() {
            return new StringJoiner(", ", DelayedItem.class.getSimpleName() + "[", "]")
                    .add("value=" + value)
                    .add("time=" + time)
                    .toString();
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return time - System.currentTimeMillis();
        }


        @Override
        public int compareTo(Delayed o) {
            return (int) (this.time - ((DelayedItem)o).time);
        }
    }

    static DelayQueue<DelayedItem<Integer>> queue = new DelayQueue<>();

    public static void main(String[] args) {
        /*
          生产者线程
         */
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                queue.offer(new DelayedItem<>(i, i * 1000));
            }
        }).start();

        /*
          消费者线程
         */
        new Thread(() -> {
            while (true) {
                try {
                    DelayedItem<Integer> delay = queue.take();
                    System.out.println(delay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
